<?php
/**
 * Create by PhpStorm
 * User: lijia
 * Data: 2020/8/10
 * Time: 10:52
 */

namespace app\api\business;


use app\api\controller\UserCommon;
use app\api\model\Address;
use think\facade\Db;

class AddressBus extends UserCommon
{

    public $model;
    public function __construct(){
        parent::__construct();
        $this->model = new Address();
    }

    public function getList($where){
        return $this->model->where($where)->order('is_default','desc')->select();
    }

    public function get($id){
        return $this->model->find($id);
    }

    public function add($data){
        if (!$this->model->where('user_id',$this->user_id)->find()){
            $data['is_default'] = 1;
        }else{
            if (isset($data['is_default']) && $data['is_default'] == 1){
                $this->model->where('user_id',$this->user_id)->save(['is_default' => 0]);
            }
        }
        return $this->model->insert($data);
    }

    public function save($data){
        if (isset($data['is_default']) && $data['is_default'] == 1){
            $this->model->where('user_id',$this->user_id)->save(['is_default' => 0]);
        }
        return $this->model->where('id',$data['id'])->save($data);
    }

    public function delete($id){
        return $this->model->where('id',$id)->delete();
    }

    public function setDefault($id){
        $this->model->where('user_id',$this->user_id)->save(['is_default' => 0]);
        $this->model->where('id',$id)->save(['is_default' => 1]);
    }
}